<template>
  <div class="message-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索消息内容/发送者/接收者"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        style="width: 300px"
      >
        <template #prefix>
          <i class="el-icon-search"></i>
        </template>
      </el-input>
      <el-select
        v-model="statusFilter"
        placeholder="消息状态"
        clearable
        @change="handleSearch"
        style="width: 120px; margin-left: 10px"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <!-- 消息表格 -->
    <el-table
      v-loading="loading"
      :data="filteredMessages"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="messageId"
        label="ID"
        width="220"
      />
      <el-table-column
        prop="content"
        label="消息内容"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="senderNickname"
        label="发送者"
        width="120"
      />
      <el-table-column
        prop="receiverNickname"
        label="接收者"
        width="120"
      />
      <el-table-column
        prop="isRead"
        label="状态"
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type="row.isRead ? 'success' : 'warning'">
            {{ row.isRead ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="发送时间"
        width="180"
      >
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="150"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            @click="handleView(row)"
            plain
          >
            查看
          </el-button>
          <el-button
            size="small"
            class="delete-btn"
            @click="handleDelete(row)"
            plain
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 消息详情对话框 -->
    <el-dialog
      title="消息详情"
      v-model="detailDialogVisible"
      width="500px"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-item">
          <span class="label">消息ID：</span>
          <span>{{ currentMessage.messageId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">发送者：</span>
          <span>{{ currentMessage.senderNickname }}</span>
        </div>
        <div class="detail-item">
          <span class="label">接收者：</span>
          <span>{{ currentMessage.receiverNickname }}</span>
        </div>
        <div class="detail-item" v-if="currentMessage.user">
          <span class="label">用户详情：</span>
          <div class="user-details">
            <div v-if="currentMessage.user.studentId">学号：{{ currentMessage.user.studentId }}</div>
            <div v-if="currentMessage.user.phone">手机：{{ currentMessage.user.phone }}</div>
          </div>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <el-tag :type="currentMessage.isRead ? 'success' : 'warning'">
            {{ currentMessage.isRead ? '已读' : '未读' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">内容：</span>
          <div class="content">{{ currentMessage.content }}</div>
        </div>
        <div class="detail-item">
          <span class="label">发送时间：</span>
          <span>{{ formatDate(currentMessage.createTime) }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import messageService from '@/services/message.service'
import userService from '@/services/user.service'

export default {
  name: 'MessageManagement',
  data() {
    return {
      messages: [],
      loading: false,
      searchQuery: '',
      statusFilter: '',
      detailDialogVisible: false,
      currentMessage: null,
      statusOptions: [
        { value: 0, label: '未读' },
        { value: 1, label: '已读' }
      ],
      userList: []
    }
  },
  computed: {
    // 过滤消息列表
    filteredMessages() {
      let result = this.messages

      // 状态过滤
      if (this.statusFilter !== '') {
        result = result.filter(message => (message.isRead ? 1 : 0) === this.statusFilter)
      }

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(message => 
          (message.content && message.content.toLowerCase().includes(query)) ||
          (message.senderNickname && message.senderNickname.toLowerCase().includes(query)) ||
          (message.receiverNickname && message.receiverNickname.toLowerCase().includes(query))
        )
      }

      return result
    }
  },
  mounted() {
    this.fetchAllUsersAndMessages()
  },
  methods: {
    // 获取消息列表
    async fetchMessages() {
      try {
        this.loading = true
        const response = await messageService.getMessages()
        console.log('消息API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的消息数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'messages', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到消息数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到消息数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          // 处理消息数据，确保字段映射正确
          this.messages = (data || []).map(message => {
            console.log('处理消息数据:', message)
            console.log('当前用户列表:', this.userList)
            
            // 根据userId查找用户昵称
            let receiverNickname = '未知用户'
            if (message.userId) {
              console.log('查找用户ID:', message.userId)
              const user = this.userList.find(u => u.userId === message.userId)
              console.log('找到的用户:', user)
              if (user) {
                if (user.nickname && user.nickname.trim()) {
                  receiverNickname = user.nickname
                } else if (user.studentId && user.studentId.trim()) {
                  receiverNickname = user.studentId
                }
              }
            }
            
            return {
              ...message,
              messageId: message.messageId || message.id || '未知消息',
              content: message.content || '未知内容',
              // 消息是系统发送给用户的，所以发送者是系统，接收者是关联的用户
              senderNickname: '系统',
              receiverNickname: receiverNickname,
              isRead: message.isRead === 1 || message.isRead === true,
              createTime: message.createTime || message.createDate
            }
          })
          
          console.log('处理后的消息列表:', this.messages)
          console.log('消息列表长度:', this.messages.length)
        } else {
          console.error('API返回错误:', response)
          this.messages = []
          Message.error(response?.message || '获取消息列表失败')
        }
      } catch (error) {
        console.error('获取消息列表失败:', error)
        this.messages = []
        Message.error(error?.response?.data?.message || '获取消息列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      // 搜索逻辑已通过计算属性实现
    },

    // 查看消息详情
    async handleView(row) {
      try {
        if (!row.isRead) {
          await messageService.markAsRead(row.messageId)
          row.isRead = true
        }
        this.currentMessage = row
        this.detailDialogVisible = true
      } catch (error) {
        console.error('标记消息已读失败:', error)
        Message.error(error?.response?.data?.message || '标记消息已读失败')
      }
    },

    // 删除消息
    async handleDelete(row) {
      try {
        await MessageBox.confirm('确定要删除这条消息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await messageService.deleteMessage(row.messageId)
        Message.success('删除成功')
        await this.fetchAllUsersAndMessages()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除消息失败:', error)
          Message.error(error?.response?.data?.message || '删除失败')
        }
      }
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString()
    },

    async fetchAllUsersAndMessages() {
      try {
        await this.fetchUsers()
        await this.fetchMessages()
      } catch (error) {
        console.error('获取用户和消息失败:', error)
        Message.error(error?.response?.data?.message || '获取用户和消息失败')
      }
    },

    async fetchUsers() {
      try {
        const response = await userService.getUsers()
        console.log('用户API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的用户数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'users', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到用户数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到用户数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          this.userList = data || []
          console.log('获取用户列表成功:', this.userList)
          console.log('用户列表长度:', this.userList.length)
        } else {
          console.error('API返回错误:', response)
          this.userList = []
          Message.error(response?.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.userList = []
        Message.error(error?.response?.data?.message || '获取用户列表失败')
      }
    }
  }
}
</script>

<style scoped>
.message-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}

.message-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item .label {
  width: 80px;
  color: #606266;
  font-weight: bold;
}

.detail-item .content {
  flex: 1;
  white-space: pre-wrap;
  word-break: break-all;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.user-details > div {
  padding: 4px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}
</style> 